from gibe.plugin import Plugin
from gibe.model import Post

from turbogears import controllers
import routes

class ShortUrlRedirectController(controllers.Controller):
    def redirect(self, blog, action, year, month, day, slug):
        post = Post.get_by(slug=slug)
        raise routes.redirect_to('posts', post=post)

class GibeShortUrlsPlugin(Plugin):
    """
    This plugin overrides the default "posts" route, generating and responding
    to URLs based only on slug, for shorter (and perhaps more SEO-friendly)
    URLs.
    """

    def map_routes(self, blog, mapper, controllers):
        """
        General plan:

        1. Find the current "posts" route.
        2. Copy it
        3. Replace the URL portion with just the :slug
        4. Replace the post_expand filter so that URLs don't have excess
           arguments (year, month...)
        5. Add a condition function that makes this route conditional of the
           slug existing in the Post table.
        6. Insert the route before the existing "posts" route.
        """

        for m in mapper:
            if m[0] == "posts":
                post_route_tuple = m
                break
        else:
            # Can't find "posts" route - guess we can't augment it then...
            return

        post_route = list(post_route_tuple)

        # replace route URL
        post_route[1] = ":slug"

        # replace filter
        def post_expand(kargs):
            kargs.pop('year', None)
            kargs.pop('month', None)
            kargs.pop('day', None)

            if 'post' not in kargs:
                return kargs

            post = kargs.pop('post')
            kargs['slug'] = post.slug

            return kargs
        post_route[2]['_filter'] = post_expand

        # add condition function
        def post_condition(environ, match_dict):
            slug = match_dict['slug']
            post = Post.get_by(slug=slug)
            if not post:
                return False
            
            match_dict['year'] = post.creation_time.year
            match_dict['month'] = "%02d" % (post.creation_time.month,)
            match_dict['day'] = "%02d" % (post.creation_time.day,)

            return True
        post_route[2]['conditions'] = dict(function=post_condition)


        controllers['gibeshorturls.ShortUrlRedirectController'] = ShortUrlRedirectController()
        redirect_route = ('gibeshorturls.redirect', post_route_tuple[1], dict(controller='gibeshorturls.ShortUrlRedirectController', action="redirect", conditions=dict(function=post_condition)))

        print post_route_tuple
        print redirect_route

        i = mapper.index(post_route_tuple)
        mapper[i] = redirect_route
        mapper.insert(i, tuple(post_route))

        return
